import { connect } from "react-redux";
import { setFeching,fetchHotAsync } from "./store/actions";

function App({ loading, list, addFn, setLoading, fetchHotCities }) {
  return (
    <div className="App" style={{ opacity: loading ? 0.5 : 1 }}>
      {loading && <h3>Loading...</h3>}

      <ul>
        {
          list.map(
            city => <li key={city}>{city}</li>
          )
        }
      </ul>
      <hr />

      {/* <button onClick={() => console.log(addFn(2, 3))}>setLoading</button> */}

      <button onClick={() => {
        setLoading(Date.now() % 2 === 1)
      }}>setLoading</button>

      <button onClick={fetchHotCities}>获取热门城市</button>
    </div>
  );
}

/* 注入数据订阅 */
const mapStateToProps = (state) => {
  return {
    loading: state.isFetching,
    list: state.hotCities
  }
}

/* 注入增删改查 */
const mapDispatchToProps = (dispatch) => {
  return {
    addFn: (a, b) => a + b,

    setLoading: (value) => dispatch(
      // { type: "SET_FETCHING", value }
      setFeching(value)
    ),

    fetchHotCities: () => {
      // 派发一个异步action以获取城市列表
      dispatch(
        fetchHotAsync()
      )
    }
  }
}

/*  */
export default connect(mapStateToProps, mapDispatchToProps)(App)